package mysql_svc

import (
	"gitee.com/visons/gopkg/logger"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"sync"
	"time"
	"web-model/config"
)

type mysqlDB struct {
	db *gorm.DB
}

var mysqlInstance *mysqlDB
var instanceOne sync.Once

func NewMysqlDB() *mysqlDB {
	instanceOne.Do(func() {
		mysqlInstance = new(mysqlDB)
		mysqlInstance.initDB()
	})
	return mysqlInstance
}

func (m *mysqlDB) initDB() {
	conf := config.GetConfig().Mysql

	db, err := gorm.Open("mysql", conf.Dsn)
	if err != nil {
		logger.Painc("connect db dsn %s error %v", conf.Dsn, err)
	}

	db.DB().SetMaxOpenConns(conf.MaxOpenConns)
	db.DB().SetMaxIdleConns(conf.MaxIdleConns)
	db.DB().SetConnMaxLifetime(time.Second * time.Duration(conf.ConnMaxLifetime))
	db.LogMode(conf.PrintSql)
	m.db = db
}

func (m *mysqlDB) GetDB() *gorm.DB {
	return m.db
}
